<?php

namespace Biz\Services\Site;

use Lumen\Logger\Logger;
use Illuminate\Http\Request;
use Biz\Models\Site\SiteNews;
use Biz\Libraries\TranslationUtil;
use Illuminate\Support\Facades\DB;
use Biz\Models\Site\SiteNewsCategory;
use Biz\Constants\Site\SiteNewsConstants;
use Biz\Criteria\Site\SiteFilterCriterion;
use Biz\Criteria\Site\LocaleFilterCriterion;
use Lumen\Core\Exceptions\BusinessException;
use Biz\Repositories\Site\SiteNewsRepository;
use Illuminate\Contracts\Pagination\Paginator;

/**
 * SiteNewsService.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class SiteNewsService
{
    /**
     * @var \Lumen\Repository\Contracts\RepositoryContract
     */
    protected $repository;

    /**
     * @var SiteNewsCategoryService
     */
    protected $categoryService;

    /**
     * RepositoryController constructor.
     *
     * @param SiteNewsRepository      $repository
     * @param SiteNewsCategoryService $categoryService
     */
    public function __construct(SiteNewsRepository $repository, SiteNewsCategoryService $categoryService)
    {
        $this->repository                   = $repository;
        $this->categoryService              = $categoryService;
    }

    /**
     * 列表页.
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|mixed
     */
    public function index(Request $request): Paginator
    {
        $site_id  = $request->get('site_id');
        $pageSize = $request->get('page_size', 10);

        $results = $this->repository
            ->with(['category','translations'])
            ->setCacheLifetime(0)
            ->pushCriterion(new SiteFilterCriterion($site_id))
            //->pushCriterion(new LocaleFilterCriterion())
            ->paginate($pageSize);

        return $results;
    }

    /**
     * Find.
     *
     * @param int $id
     *
     * @throws BusinessException
     *
     * @return SiteNews
     */
    public function find(int $id): SiteNews
    {
        $news = $this->repository->find($id);
        if (is_null($news)) {
            throw new BusinessException(trans('site/news/news.not_found'));
        }

        return $news;
    }

    /**
     * Find By uid.
     *
     * @param string $uid
     *
     * @throws BusinessException
     *
     * @return SiteNews
     */
    public function findByUid(string $uid): SiteNews
    {
        $id   = SiteNews::decodeUid($uid);

        return $this->find($id);
    }

    /**
     * With find.
     *
     * @param int   $id
     * @param array $with
     *
     * @throws BusinessException
     *
     * @return SiteNews
     */
    public function findWith(int $id, $with = []): SiteNews
    {
        $site = $this->repository->with($with)->find($id);
        if (is_null($site)) {
            throw new BusinessException(trans('site/news/news.not_found'));
        }

        return $site;
    }

    /**
     * Find By Site Id.
     *
     * @param int $site_id
     *
     * @throws BusinessException
     *
     * @return bool
     */
    public function findBySiteId(int $site_id)
    {
        $news = $this->repository
            ->pushCriterion(new SiteFilterCriterion($site_id))
            ->findFirst();

        return $news;
    }

    /**
     * Handle Category Id.
     *
     * @param array $data
     *
     * @return array
     */
    public function handleCategoryId(array $data): array
    {
        $category_id = $data['category_id'];
        if (SiteNewsConstants::CATEGORY_NONE === $category_id) {
            $data['category_id'] = SiteNewsConstants::CATEGORY_DEFAULT;
        } else {
            /** @var SiteNewsCategory $category */
            $category            = $this->categoryService->findByUid($category_id);
            $data['category_id'] = $category->id;
        }

        return $data;
    }

    /**
     * Create.
     *
     * @param array $data
     *
     * @throws \Exception
     *
     * @return SiteNews
     */
    public function create(array $data): SiteNews
    {
        // Handle Category
        $data = $this->handleCategoryId($data);

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            // 创建介绍
            $data['status'] = SiteNewsConstants::STATUS_NORMAL;

            $data = TranslationUtil::convertTranslationsData($data);

            $news   = $this->repository->create($data);
            if (! $news) {
                throw new BusinessException(trans('site/news/news.create_fail'));
            }
            // Load Translations
            $news->load('translations');

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $news;
    }

    /**
     * Detail.
     *
     * @param string $id
     *
     * @throws BusinessException
     *
     * @return SiteNews
     */
    public function show(string $id): SiteNews
    {
        $id   = SiteNews::decodeUid($id);
        $site = $this->findWith($id, ['category', 'category.translations','translations']);

        return $site;
    }

    /**
     * Edit.
     *
     * @param string $id
     * @param array  $data
     *
     * @throws \Exception
     *
     * @return SiteNews
     */
    public function edit(string $id, array $data): SiteNews
    {
        $id   = SiteNews::decodeUid($id);

        return $this->update($id, $data);
    }

    /**
     * Update.
     *
     * @param int   $id
     * @param array $data
     *
     * @throws \Exception
     *
     * @return SiteNews
     */
    public function update(int $id, array $data): SiteNews
    {
        $news = $this->find($id);

        // Handle Category
        $data = $this->handleCategoryId($data);

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            $data = TranslationUtil::convertTranslationsData($data);

            $news   = $this->repository->update($news, $data);
            if (! $news) {
                throw new BusinessException(trans('site/news/news.create_fail'));
            }

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $news;
    }

    /**
     * Remove.
     *
     * @param string $id
     *
     * @throws \Exception
     *
     * @return bool
     */
    public function remove(string $id): bool
    {
        $id   = SiteNews::decodeUid($id);

        return $this->delete($id);
    }

    /**
     * Delete.
     *
     * @param int $id
     *
     * @throws \Exception
     *
     * @return bool
     */
    public function delete(int $id): bool
    {
        /** @var SiteNews $news */
        $news = $this->find($id);

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            $this->repository->delete($news);

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return true;
    }

    /**
     * Delete Translations.
     *
     * @param string $id
     * @param string $locale
     *
     * @return bool
     */
    public function deleteTranslations(string $id, string $locale): bool
    {
        /** @var SiteNews $news */
        $news = $this->findByUid($id);

        $news->deleteTranslations($locale);

        return true;
    }

    /**
     * 设置指定新闻的分类ID为默认值
     *
     * @param int $category_id
     *
     * @return bool
     */
    public function categoryDefault(int $category_id): bool
    {
        /** @var SiteNews $news */
        SiteNews::where('category_id', $category_id)->update([
            'category_id' => 0
        ]);

        return true;
    }
}
